import type { Library, HistoricalEvent } from "@/types"

export function getRandomEvents(libraries: Library[], count: number): HistoricalEvent[] {
  const allEvents = libraries.flatMap((library) => library.events)
  
  // 随机打乱事件顺序
  const shuffled = [...allEvents].sort(() => Math.random() - 0.5)
  
  // 返回指定数量的事件
  return shuffled.slice(0, count)
}

export function findClosestEvent(anchorEvent: HistoricalEvent, events: HistoricalEvent[]): HistoricalEvent {
  const parseHistoricalDate = (dateString: string): number => {
    const isBC = dateString.startsWith('-')
    const cleanDateString = isBC ? dateString.substring(1) : dateString
    const [year, month, day] = cleanDateString.split("-").map(Number)
    
    // 将日期转换为天数（以公元1年1月1日为基准点）
    const yearDays = (isBC ? -year : year) * 365.25  // 考虑闰年
    const monthDays = (month - 1) * 30.44  // 月平均天数
    return yearDays + monthDays + day
  }

  const anchorDays = parseHistoricalDate(anchorEvent.date)
  
  return events.reduce((closest, current) => {
    const closestDays = parseHistoricalDate(closest.date)
    const currentDays = parseHistoricalDate(current.date)
    
    const closestDiff = Math.abs(closestDays - anchorDays)
    const currentDiff = Math.abs(currentDays - anchorDays)
    
    return currentDiff < closestDiff ? current : closest
  }, events[0])
}

